package com.jd.jobkeeper.server.service.db.impl;

import com.jd.jobkeeper.server.data.entity.ChangeLog;
import com.jd.jobkeeper.server.data.pesistence.ChangeLogRepository;
import com.jd.jobkeeper.server.service.ChangeLogService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChangeLogServiceImpl implements ChangeLogService {

    final ChangeLogRepository changeLogRepository;

    public ChangeLogServiceImpl(ChangeLogRepository changeLogRepository) {
        this.changeLogRepository = changeLogRepository;
    }

    @Override
    public long currentIndex() {
        Pageable pageable = PageRequest.of(0, 1, Sort.by(Sort.Direction.DESC, "id"));

        Specification specification = (Specification<ChangeLog>) (root, query, criteriaBuilder) -> {
            //query.orderBy(criteriaBuilder.desc(root.get("id")));
            return criteriaBuilder.conjunction();
        };
        Page<ChangeLog> p = changeLogRepository.findAll(specification, pageable);
        return p.hasContent() ? p.iterator().next().getId() : 0;
    }

    @Override
    public ChangeLog getNext(long index) {
        Pageable pageable = PageRequest.of(0, 1, Sort.Direction.ASC, "id");
        List<ChangeLog> logs = changeLogRepository.getNext(index,pageable);
        return logs.get(0);
    }
}
